/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-25 17:28:15
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-07-12 14:32:31
 */
import apiMod from '@/apiMod'
import FileSaver from 'file-saver'
import { useUserStore } from '@/stores/user'

export const hasRouteChildren = (item: any, keyname = 'children') => {
	return item[keyname] && Array.isArray(item[keyname]) && item[keyname].length > 0
}

/**
 *  树结构转为数组
 * @param source 数组
 * @param keyname 子集集合名称
 * @returns
 */
export const treeTransArray = (source: Object[], keyname = 'children') => {
	const maker = (sources, sourceItem) => {
		if (hasRouteChildren(sourceItem, keyname)) {
			sources = sources.concat(sourceItem[keyname].reduce(maker, []))
		} else {
			sources.push(sourceItem)
		}
		return sources
	}
	return source.reduce(maker, [])
}
/**
 * 数组转为树结构
 * @param array 数组
 * @param idStr 自增参数名称
 * @param pidStr 父级参数名称
 * @param children 子集集合名称
 * @param defaultPar 默认当前父级
 * @returns
 */
export const arrayTransTree = (array: Object[], idStr: string, pidStr: string, children = 'children', defaultPar = '-1') => {
	const getParId = () => {
		const data = array
			.sort((a: any, b: any) => a.regionGrade - b.regionGrade)
			.map((item: any) => item.administrationPid)
			.sort()
		return data[0] || -1
	}
	defaultPar = getParId()
	const tempArr = JSON.parse(JSON.stringify(array))
	return tempArr.filter((father) => {
		let branchArr: any = tempArr.filter((child) => father[idStr] == child[pidStr])
		if (branchArr.length > 0) {
			father[children] = branchArr
		} else {
			branchArr = ''
		}
		return father[pidStr] == defaultPar
	})
}
/**
 * 根据节点id获取父级节点集合
 * @param list
 * @param menuId
 * @param children
 * @param level
 * @returns
 */
export function treeFindList(list, menuId, children = 'children', level = 0) {
	var arrRes = []
	let obj = {
		id: 0,
		[children]: list,
	}
	if (!list) return arrRes
	let maker = (data, menuId, level) => {
		if (!data || !data[children] || !data[children].length) {
			return
		}
		for (var i = 0; i < data[children].length; i++) {
			let item = data[children][i]
			if (item.id == menuId) {
				let _obj = {
					...item,
					children: undefined,
				}
				arrRes.unshift({
					level,
					..._obj,
				})
				maker(obj, data.id, 0)
				break
			} else if (item[children] && item[children].length > 0) {
				maker(item, menuId, level + 1)
			}
		}
	}
	maker(obj, menuId, level)
	return arrRes
}

export const flatten = (data) => {
	const result = {}
	const isEmpty = (x) => Object.keys(x).length === 0
	const maker = (cur, prop) => {
		if (Object(cur) !== cur) {
			result[prop] = cur
		} else if (Array.isArray(cur)) {
			const length = cur.length
			for (let i = 0; i < length; i++) {
				maker(cur[i], `${prop}[${i}]`)
			}
			if (length === 0) {
				result[prop] = []
			}
		} else {
			if (!isEmpty(cur)) {
				Object.keys(cur).forEach((key) => maker(cur[key], prop ? `${prop}.${key}` : key))
			} else {
				result[prop] = {}
			}
		}
	}
	maker(data, '')
	return result
}

/**
 * 获取区域数据
 * @param data 对象或者数组
 * @param type name -获取名称/获取对象
 * @returns
 */
export const getAreaObj = (data?: any, tag?: string, type?: string, suffix?: string) => {
	if (!tag) {
		tag = ''
	}
	if (!suffix && suffix !== null) {
		suffix = 'Id'
	} else if (suffix == null) {
		suffix = ''
	}
	function toCamelCase(str) {
		return str.replace(/[-_](.)/g, function (match, group1) {
			return tag ? group1.toUpperCase() : group1
		})
	}
	if (Array.isArray(data)) {
		const areaData = [...data]
		let areaObj = {}
		areaObj[toCamelCase(`${tag}_province${suffix}`)] = areaData[0] || ''
		areaObj[toCamelCase(`${tag}_city${suffix}`)] = areaData[1] || ''
		areaObj[toCamelCase(`${tag}_area${suffix}`)] = areaData[2] || ''
		areaObj[toCamelCase(`${tag}_street${suffix}`)] = areaData[3] || ''
		areaObj[toCamelCase(`${tag}_community${suffix}`)] = areaData[4] || ''
		return areaObj
	} else if (typeof data === 'string') {
		const areaName = data.split('/')
		let areaNameObj = {}
		areaNameObj[toCamelCase(`${tag}_provinceName`)] = areaName[0] || ''
		areaNameObj[toCamelCase(`${tag}_cityName`)] = areaName[1] || ''
		areaNameObj[toCamelCase(`${tag}_areaName`)] = areaName[2] || ''
		areaNameObj[toCamelCase(`${tag}_streetName`)] = areaName[3] || ''
		areaNameObj[toCamelCase(`${tag}_communityName`)] = areaName[4] || ''
		return areaNameObj
	} else if (data && !type) {
		return [
			data[toCamelCase(`${tag}_provinceName`)],
			data[toCamelCase(`${tag}_cityName`)],
			data[toCamelCase(`${tag}_areaName`)],
			data[toCamelCase(`${tag}_streetName`)],
			data[toCamelCase(`${tag}_communityName`)],
		]
			.filter(Boolean)
			.join('/')
	} else if (data && type) {
		const names = [
			data[toCamelCase(`${tag}_provinceName`)],
			data[toCamelCase(`${tag}_cityName`)],
			data[toCamelCase(`${tag}_areaName`)],
			data[toCamelCase(`${tag}_streetName`)],
			data[toCamelCase(`${tag}_communityName`)],
		]
			.filter(Boolean)
			.join('/')

		const areaIds = [
			data[toCamelCase(`${tag}_provinceId`)],
			data[toCamelCase(`${tag}_cityId`)],
			data[toCamelCase(`${tag}_areaId`)],
			data[toCamelCase(`${tag}_streetId`)],
			data[toCamelCase(`${tag}_communityId`)],
		].filter((item) => item && item !== -1)
		return {
			names,
			areaIds,
		}
	} else {
		return {}
	}
}
/**
 * 正则校验规则
 * phone: 手机号
 * code: 社会统一信用代码
 * idCard: 身份证号
 * idCard: 身份证号
 * number： 保留2位小数据的数字输入校验
 */
export const regularRule = {
	phone: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
	code: /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/,
	idCard: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
	areaCode: /^([1-9]d {5}$)/,
	postalCode: /(^\d{5}$)|(^\d{5}-\d{4}$)/,
	fixedTwoNum: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, // 保留两位数字校验
  httpOrhttps:/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/,// 判断是否http或https 开头
	number: (rule: any, value: any, callback: any) => {
		if (!value) {
			callback()
		} else {
			const reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/
			// const reg = /^[0-9]*$/
			const test = new RegExp(reg)
			if (!test.test(value)) {
				callback(new Error('请输入正确的数值'))
			}
			callback()
		}
	},
}

export const uploadType = {
	fileMetaType:
		'application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf,application/word,image/png,image/jpg,image/jpeg,video/mp4,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,',
	imgMetaType: '',
}

/**
 * 重要信息使用*替代
 * @param {*} str
 * @param {*} frontLen
 * @param {*} endLen
 */
export const plusXing = (str: any, frontLen = 3, endLen = 4) => {
	if (str) {
		let len = str.length - frontLen - endLen
		let xing = ''
		for (let i = 0; i < len; i++) {
			xing += '*'
		}
		return str.substring(0, frontLen) + xing + str.substring(str.length - endLen)
	}
}

/**
 * 计算两个时间戳之间相差的天数
 * @param {*} blockingTime 时间戳
 */
// 计算两个时间戳之间相差的天数
export const getDaysAndHours = (blockingTime: any) => {
	let dateNow = new Date() // 获取当前时间
	let timeDiff = Math.abs(blockingTime - dateNow.getTime()) // 时间差的毫秒数
	// timeDiff = 时间戳差值

	let days = Math.floor(timeDiff / (24 * 3600 * 1000)) // 计算出天数
	let leavel1 = timeDiff % (24 * 3600 * 1000) // 计算天数后剩余的时间
	let hours = Math.floor(leavel1 / (3600 * 1000)) // 计算天数后剩余的小时数
	// let leavel2 = timeDiff % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
	// let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
	if (days != 0) {
		return days + '天' + hours + '小时'
	} else {
		return hours + '小时'
	}
}

/**
 * 指定日期格式化
 * @param date
 * @returns
 */
export const formateDate = (date?: Date,showTime?:boolean) => {
	if (!date) date = new Date()
	const year = date.getFullYear()
	const month = (date.getMonth() + 1).toString().padStart(2, '0')
	const day = date.getDate().toString().padStart(2, '0')
	if(showTime){
		const hours = date.getHours().toString().padStart(2, '0')
		const min = date.getMinutes().toString().padStart(2, '0')
		const sec = date.getSeconds().toString().padStart(2, '0')
		console.log('看看',hours,min,sec)
		return `${year}-${month}-${day} ${hours}:${min}:${sec}`
	}
	return `${year}-${month}-${day}`
}

// 防抖
let timeout
export function debounce(func, wait, immediate?) {
	let fun = function (...args) {
		let context = this
		if (timeout) clearTimeout(timeout)
		if (immediate == true) {
			let callNow = !timeout
			timeout = setTimeout(function () {
				timeout = null
			}, wait)
			if (callNow) func.apply(context, args)
		} else {
			timeout = setTimeout(function () {
				func.apply(context, args)
			}, wait)
		}
	}
	return fun()
}
// 节流
let timer = null
export function throttle(fn, delay = 500, duration = 1000) {
	var that = this
	var begin = new Date().getTime()
	let ff = function () {
		var context = that
		var args = arguments
		var current = new Date().getTime()
		clearTimeout(timer)
		if (current - begin >= duration) {
			fn.apply(context, args)
			begin = current
		} else {
			timer = setTimeout(function () {
				fn.apply(context, args)
			}, delay)
		}
	}
	return ff()
}
/**
 * obs 图片预览
 * @param path
 * @returns
 */
export const DowloadPreviewImage = (path: string, type?: string) => {
	return new Promise((resolve, reject) => {
		const fileName: any = decodeURIComponent(path).split('/').slice(-1).toString()
		apiMod
			.previewFileDowload(fileName)
			.then((blob) => {
				let url = window.URL.createObjectURL(blob)
				if (type == 'blob') {
					resolve(blob)
				} else {
					resolve(url)
				}
			})
			.catch((error) => {
				reject(error)
			})
	})
}

/**
 * 删除上传obs 的文件
 * @param path 文件路径
 * @returns
 */
export const DeleteObsFile = (path: string) => {
	return new Promise((resolve, reject) => {
		const fileName: any = decodeURIComponent(path).split('/').slice(-1).toString()
		apiMod
			.view_obs_delete(fileName)
			.then((blob) => {
				resolve(blob)
			})
			.catch((error) => {
				reject(error)
			})
	})
}
// base64转换为file
export const Base64UrlToBlob = (urlData) => {
	const bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte
	// 处理异常,将ascii码小于0的转换为大于0
	const ab = new ArrayBuffer(bytes.length)
	const ia = new Uint8Array(ab)
	for (let i = 0; i < bytes.length; i++) {
		ia[i] = bytes.charCodeAt(i)
	}
	return new Blob([ab], { type: 'image/png' })
}
/** 数字金额大写转换(可以处理整数,小数,负数) */

export const dealBigMoney = (n: number) => {
	const fraction = ['角', '分']
	const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
	const unit = [
		['元', '万', '亿'],
		['', '拾', '佰', '仟'],
	]
	let head = n < 0 ? '欠' : ''
	n = Math.abs(n)

	let s = ''

	for (let i = 0; i < fraction.length; i++) {
		s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
	}
	s = s || '整'
	n = Math.floor(n)

	for (let i = 0; i < unit[0].length && n > 0; i++) {
		let p = ''
		for (let j = 0; j < unit[1].length && n > 0; j++) {
			p = digit[n % 10] + unit[1][j] + p
			n = Math.floor(n / 10)
		}
		s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
	}
	return (
		head +
		s
			.replace(/(零.)*零元/, '元')
			.replace(/(零.)+/g, '零')
			.replace(/^整$/, '零元整')
	)
}

/**
 * 获取文件流，并获取响应头中的文件信息，需要后端跨域支持
 */
export const onDownloadFile = async (url: string, params?: any) => {
	const baseUrl = import.meta.env.MODE == 'development' ? import.meta.env.VITE_BASE_API : window.location.origin
	const request = {
		body: JSON.stringify(params),
		method: 'POST',
		headers: {
			'Content-Type': 'application/json;charset=UTF-8',
		},
	}
	const response = await fetch(baseUrl + url, request)
	const filename = response.headers.get('Content-Disposition').split(';')[1].split('=')[1]
	const blob = await response.blob()
	FileSaver.saveAs(blob, decodeURI(filename))
}
// 过滤对象中的空值
export const filterEmptyObj = (objdata: any) => {
	const flat = (item, preKey = '', res = {}) => {
		Object.entries(item).forEach(([key, val]) => {
			if (val && typeof val === 'object' && !Array.isArray(val)) {
				flat(val, preKey + key + '.', res)
			} else {
				res[preKey + key] = val
			}
		})
		return res
	}
	const fileterEmpty = (obj: any) => {
		const filteredObj = Object.fromEntries(
			Object.entries(obj).filter(([key, value]) => {
				// 过滤空值
				return value !== '' && value !== null && value !== undefined
			})
		)
		return filteredObj
	}
	const unflat = (data) => {
		if (Object(data) !== data || Array.isArray(data)) return data
		var regex = /\.?([^.\[\]]+)|\[(\d+)\]/g,
			resultholder = {}
		for (var p in data) {
			var cur = resultholder,
				prop = '',
				m
			while ((m = regex.exec(p))) {
				cur = cur[prop] || (cur[prop] = m[2] ? [] : {})
				prop = m[2] || m[1]
			}
			cur[prop] = data[p]
		}
		return resultholder[''] || resultholder
	}
	return objdata ? unflat(fileterEmpty(flat(objdata))) : {}
}

export const getMonthStartEnd = (y, m) => {
	let mon
	const firstDay = new Date(y, m, 1) // 取当年当月中的第一天
	const currentMonth = firstDay.getMonth() //取得月份数
	const lastDay = new Date(firstDay.getFullYear(), currentMonth + 1, 0).getDate() // 获取当月最后一天日期
	if (firstDay.getMonth() < 10) {
		mon = '0' + firstDay.getMonth()
	} else {
		mon = firstDay.getMonth()
	}
	const startDate = firstDay.getFullYear() + '-' + mon + '-' + '0' + firstDay.getDate()
	const endDate = firstDay.getFullYear() + '-' + mon + '-' + lastDay
	if (m == 12) {
		return [`${y}-12-01`, `${y}-12-31`].join(',')
	} else {
		return [startDate, endDate].join(',')
	}
}

export function DateDiffer(Date_end) {
	if (!Date_end) return 0
	let end = new Date(Date_end)
	let start = new Date()
	end = new Date(end.getFullYear(), end.getMonth(), end.getDate())
	start = new Date(start.getFullYear(), start.getMonth(), start.getDate())
	const diff = end.getTime() - start.getTime()
	const diffDate = diff / (24 * 60 * 60 * 1000) //计算当前时间与结束时间之间相差天数
	return diffDate
}
/**
 * 身份证获取年龄
 * @param idCard 身份证号
 * @returns
 */
export function getAgeFromIdCard(idCard: string) {
	// 提取出生日期
	const birthDate = idCard.substring(6, 14)

	// 将字符串转换为日期对象
	const birthYear = parseInt(birthDate.slice(0, 4))
	const birthMonth = parseInt(birthDate.slice(4, 6))
	const birthDay = parseInt(birthDate.slice(6, 8))
	const birth = new Date(birthYear, birthMonth - 1, birthDay)

	// 获取今天的日期
	const today = new Date()

	// 计算年龄
	let ageDiff = today.getFullYear() - birth.getFullYear()

	// 检查是否已过生日，如果还没过，则年龄减一
	if (today.getMonth() < birth.getMonth() || (today.getMonth() === birth.getMonth() && today.getDate() < birth.getDate())) {
		ageDiff--
	}

	return ageDiff
}
// 判断是否有权限
export function isAuth(auth: string) {
	const userStore = useUserStore()
	if (auth) {
		const permissions = userStore.permissions
		let keys = Object.keys(permissions)
		let obj = keys.find((el) => {
			return el == auth
		})
		if (obj) {
			return true
		} else {
			return false
		}
	} else {
		return false
	}
}
// 传入区域，判断当前所在层级
export const getBaseAreaData = (userInfo={},level=['authProvince', 'authCity', 'authArea', 'authStreet', 'authCommunity']) => {
	// 拿到上一级
	let list = level.map((el) => {
		return userInfo[el]
	})
	list = list.filter(Boolean)
	let parentId = ''
	let myAreaId = ''
	let grandId = ''
	if (list.length > 1) {
		myAreaId = list[list.length - 1]
		if (list.length >= 2) {
			parentId = list[list.length - 2]
		}
		if (list.length >= 3) {
			grandId = list[list.length - 3]
		}
	} else if (list.length == 1) {
		parentId = list[0]
		myAreaId = list[0]
		grandId = list[0]
	}
	// 获取名称
	return {
		myAreaId,
		parentId,
		grandId,
		length: list.length,
	}
}
